// lib.rs - 用于Android构建的库入口文件

use serde::{Deserialize, Serialize};
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use sysinfo::System;
use tauri_plugin_autostart::MacosLauncher;
use tokio::sync::{Mutex, RwLock};

pub mod bandwidth;
pub mod commands;
pub mod tray;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum BandwidthLevel {
    #[serde(rename = "off")]
    Off,
    #[serde(rename = "micro")]
    Micro,
    #[serde(rename = "mini")]
    Mini,
    #[serde(rename = "low")]
    Low,
    #[serde(rename = "medium")]
    Medium,
    #[serde(rename = "high")]
    High,
    #[serde(rename = "turbo")]
    Turbo,
    #[serde(rename = "ultra")]
    Ultra,
    #[serde(rename = "extreme")]
    Extreme,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BandwidthStatus {
    pub level: BandwidthLevel,
    pub is_running: bool,
    pub bytes_consumed: u64,
    pub duration_seconds: u64,
    pub current_speed_mbps: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemInfo {
    pub ip_address: String,
    pub network_type: String,
    pub connection_status: String,
    pub cpu_usage: f64,
    pub memory_usage: f64,
    pub network_interface: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkStats {
    pub peak_speed: f64,
    pub average_speed: f64,
    pub efficiency: f64,
    pub run_count: u32,
    pub avg_session_time: u32,
    pub weekly_run_time: f64,
    pub weekly_data_usage: f64,
}

impl Default for NetworkStats {
    fn default() -> Self {
        Self {
            peak_speed: 0.0,
            average_speed: 0.0,
            efficiency: 0.0,
            run_count: 0,
            avg_session_time: 0,
            weekly_run_time: 0.0,
            weekly_data_usage: 0.0,
        }
    }
}

pub struct AppState {
    pub bandwidth_controller: Arc<RwLock<bandwidth::BandwidthController>>,
    pub is_running: Arc<AtomicBool>,
    pub system: Arc<Mutex<System>>,
    pub network_stats: Arc<Mutex<NetworkStats>>,
}

impl Default for AppState {
    fn default() -> Self {
        Self {
            bandwidth_controller: Arc::new(RwLock::new(bandwidth::BandwidthController::default())),
            is_running: Arc::new(AtomicBool::new(false)),
            system: Arc::new(Mutex::new(System::new_all())),
            network_stats: Arc::new(Mutex::new(NetworkStats::default())),
        }
    }
}

// Android应用入口点
#[cfg(target_os = "android")]
#[tauri::mobile_entry_point]
pub fn main() {
    let builder = tauri::Builder::default()
        .plugin(tauri_plugin_autostart::init())
        .plugin(tauri_plugin_log::Builder::default().build())
        .manage(AppState::default())
        .invoke_handler(tauri::generate_handler![
            commands::init_mobile,
            commands::start_bandwidth_consumption,
            commands::stop_bandwidth_consumption,
            commands::get_bandwidth_status,
            commands::get_system_info,
            commands::get_network_stats,
            commands::get_available_bandwidth_levels,
            commands::get_bandwidth_level_info,
            commands::exit_app,
            commands::prevent_default_exit,
            commands::handle_back_button,
            commands::get_platform_info
        ])
        .setup(|app| {
            // Android专用设置
            #[cfg(target_os = "android")]
            {
                // 监听Android系统事件
                let _app_handle = app.handle().clone();

                // 在Android上，我们可以通过webview的消息传递来处理返回键
                // 这里设置一个监听器，当收到返回键事件时发出自定义事件
                tauri::async_runtime::spawn(async move {
                    // 这个会在需要时由前端触发
                    println!("Android环境初始化完成，准备处理返回键事件");
                });
            }

            Ok(())
        });

    builder
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

// 桌面应用入口点
#[cfg(not(target_os = "android"))]
pub fn run() {
    tauri::Builder::default()
        .manage(AppState::default())
        // 设置应用初始化
        .setup(|app| {
            #[cfg(desktop)]
            {
                // 创建系统托盘
                match tray::create_tray_menu(&app.handle()) {
                    Ok(_) => println!("系统托盘创建成功"),
                    Err(e) => println!("系统托盘创建失败: {}", e),
                }
            }
            Ok(())
        })
        // 设置窗口关闭时，仅隐藏窗口不退出应用
        .on_window_event(|window, event| {
            #[cfg(desktop)]
            if let tauri::WindowEvent::CloseRequested { api, .. } = event {
                // 隐藏窗口而不是关闭
                let _ = window.hide();
                // 阻止关闭
                api.prevent_close();
            }
        })
        .plugin(tauri_plugin_dialog::init())
        .plugin(tauri_plugin_shell::init())
        .plugin(tauri_plugin_autostart::init(MacosLauncher::LaunchAgent, None))
        .invoke_handler(tauri::generate_handler![
            commands::start_bandwidth_consumption,
            commands::stop_bandwidth_consumption,
            commands::get_bandwidth_status,
            commands::get_system_info,
            commands::get_network_stats,
            commands::get_available_bandwidth_levels,
            commands::get_bandwidth_level_info,
            commands::exit_app,
            commands::get_platform_info
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
